import React, { useState, useEffect } from 'react';
import './index.less';
import './font_rq19lw0xbi/iconfont.js';
import {
  NavBar,
  Space,
  SearchBar,
  Swiper,
  JumboTabs,
  Toast,
  Dialog,
  Empty,
} from 'antd-mobile';
import {
  MessageFill,
  CalendarOutline,
  UserOutline,
  RightOutline,
} from 'antd-mobile-icons';
import { history, request } from 'umi';
import Ticket from '../component/ticket';
import Limited from '../component/limited';
import Regiment from '../component/regiment';
import Good from '../component/good/Good';
import Icon from './Icon';
import Notlogin from '../component/notLogin';
export default function index() {
  const right = (
    <div style={{ fontSize: 24 }}>
      <Space style={{ '--gap': '16px', color: 'rgb(168,168,168)' }}>
        <MessageFill
          onClick={() => {
            history.push('/info');
          }}
        />
        <CalendarOutline />
      </Space>
    </div>
  );
  const [imgList, setImgList] = useState([]);
  const [classify, setClassify] = useState([]);
  const [data3, setData3] = useState([]); //优惠券
  const [datalist, setdatalist] = useState([]);
  const [limList, setlimList] = useState([]); //限时秒杀
  const [ldone, setldone] = useState();
  const [token, setToken] = useState(sessionStorage.getItem('token') || '');
  const [key, setkey] = useState('1');
  async function imgShow() {
    let data = await request('/api/home/banner');
    if (data.code == 200) {
      setImgList(data.data);
    }
  }
  async function classfiyShow() {
    let data = await request('/api/classify/getOne');
    console.log(data, '分类数据');
    if (data.code == 200) {
      setClassify(data.data);
    }
  }
  async function goodShow() {
    let data = await request('/api/coupons/good/' + 1, { method: 'POST' });
    if (data.code == 200) {
      setData3(data.data);
    }
  }
  async function good(keys) {
    console.log(keys, 35);
    if (keys == undefined) {
      keys = 1;
    } else {
      setkey(keys);
    }
    let data = await request('/api/home/good/' + keys, { method: 'POST' });
    console.log(data, '分类数据1');
    if (data.code == 200) {
      console.log(data, '分类数据2');
      setdatalist(data.data);
    }
  }
  function scoll() {
    var t =
      window.pageYOffset ||
      document.documentElement.scrollTop ||
      document.body.scrollTop;
    var scrollup = document.querySelector('.adm-jumbo-tabs-tab-list');
    if (scrollup) {
      if (t >= 1067) {
        scrollup.style.position = 'fixed';
        scrollup.style.top = '38px';
      } else {
        scrollup.style.position = '';
        scrollup.style.top = '';
      }
    }
  }
  async function limitedShow() {
    let data = await request('/api/limite/time');
    console.log(data, 'time');
    if (data.code == 200) {
      setlimList(data.data);
    }
  }
  const [titles, settitles] = useState('');
  const [H, setH] = useState(0);
  const [M, setM] = useState(0);
  const [S, setS] = useState(0);
  var intervalID = '';
  function time(inputTime) {
    inputTime = new Date(inputTime);
    countDown();
    intervalID = setInterval(countDown, 1000);
    console.log(inputTime, 'aaaaaaaaaaaaaaaaaa');

    function countDown() {
      //获取当前时间的时间戳（单位毫秒）
      var nowTime = new Date();
      // console.log(nowTime,inputTime,M,H,S,"11111111111111");
      //把剩余时间毫秒数转化为秒
      var times = (inputTime - nowTime) / 1000;
      //计算小时数 转化为整数
      var h = parseInt((times / 60 / 60) % 24);
      //如果小时数小于 10，要变成 0 + 数字的形式 赋值给盒子
      // hour.innerHTML = h < 10 ? "0" + h : h;
      // console.log(h,"1111");
      h < 10 ? setH('0' + h) : setH(h);
      //计算分钟数 转化为整数
      var m = parseInt((times / 60) % 60);
      //如果分钟数小于 10，要变成 0 + 数字的形式 赋值给盒子
      m < 10 ? setM('0' + m) : setM(m);
      //计算描述 转化为整数
      var s = parseInt(times % 60);
      //如果秒钟数小于 10，要变成 0 + 数字的形式 赋值给盒子
      s < 10 ? setS('0' + s) : setS(s);
    }
  }
  useEffect(() => {
    getmiaosha();
    limitedShow();
    imgShow();
    classfiyShow();
    goodShow();
    good(key);
    window.addEventListener('scroll', scoll, true);
    // time()
    return () => {
      console.log(2222);
      console.log(intervalID);
      clearInterval(intervalID);
    };
  }, []);

  const getmiaosha = async () => {
    let { data } = await request('/api/limite/time', { method: 'GET' });
    console.log(data, '1111111111111111111111');
    let nowtime = Date.now();
    if (new Date(data[0].overTime) < nowtime) {
      console.log('结束了');

      console.log(data[0]._id);
      let a = request('/api/limite/time', {
        method: 'POST',
        data: { _id: data[0]._id },
      });
      getmiaosha();
      time(data[0].overTime);
    } else if (new Date(data[0].startTime) < nowtime) {
      console.log('正在进行中');
      settitles('结束');
      time(data[0].overTime);
    } else {
      time(data[0].overTime);
      settitles('开始');

      console.log('未开始');
    }
  };

  async function setDone(id) {
    console.log(id, '父组件接受');
    console.log(sessionStorage.getItem('token'));

    if (token) {
      console.log(222);
      let data = await request('/api/coupons/done/' + id, { method: 'POST' });
      console.log(data, 183);
      if (data.code == 200) {
        if (data.done) {
          console.log('跳转');
        } else {
          goodShow();
        }
      }
    } else {
      console.log(1111);

      Dialog.confirm({
        content: '请先登录',
        onConfirm: async () => {
          setTimeout(() => {
            history.push('/username');
          }, 3000);
          Toast.show({
            icon: 'loading',
            content: '加载中…',
          });
        },
      });
    }
  }
  const data1 = [
    {
      id: 1,
      img: '/upload/banner3.jpg',
      price: 9.9,
      num: 8989,
    },
    {
      id: 2,
      img: '/upload/banner2.jpg',
      price: 9.9,
      num: 8989,
    },
    {
      id: 3,
      img: '/upload/banner2.jpg',
      price: 9.9,
      num: 8989,
    },
    {
      id: 4,
      img: '/upload/banner2.jpg',
      price: 9.9,
      num: 8989,
    },
  ];
  const data2 = [
    '物美价廉',
    '超值上新',
    '特价严选',
    '官方补贴',
    '物美价廉',
    '超值上新',
    '特价严选',
    '官方补贴',
    '物美价廉',
    '超值上新',
    '特价严选',
    '官方补贴',
    '特价严选',
  ];
  return (
    <div className="home">
      <div className="homeTop">
        <NavBar right={right} backArrow={false} back={null}>
          <SearchBar
            placeholder="请输入内容"
            onFocus={() => {
              history.push('/search');
            }}
          />
        </NavBar>
      </div>
      <div className="homeBanner">
        <Swiper loop autoplay>
          {imgList.map((item) => {
            return (
              <Swiper.Item key={item._id}>
                <img src={'/api' + item.name} alt="" />
              </Swiper.Item>
            );
          })}
        </Swiper>
      </div>
      <div className="homeClassfiy">
        <div className="one">
          {classify.map((item) => {
            return (
              <div
                className="box"
                key={item._id}
                onClick={() => {
                  history.push({
                    pathname: '/Cgoods',
                    query: { id: item._id },
                  });
                }}
              >
                <div className="boxIcon">
                  <Icon type={item.icon}></Icon>
                </div>
                <p>{item.name}</p>
              </div>
            );
          })}
        </div>
      </div>
      {/* 今日好券 */}
      <div className="homeTicket">
        <div className="ticketTop">
          <span className="span1"> 今日好券</span>
          <span
            className="span2"
            onClick={() => {
              history.push('/coupons');
            }}
          >
            领券
            <RightOutline />
          </span>
        </div>
        <div className="data">
          {data3.map((item) => {
            return (
              <Ticket
                {...item}
                setDone={(id) => {
                  setDone(id);
                }}
                key={item._id}
              ></Ticket>
            );
          })}
        </div>
      </div>
      {/* 限时秒杀 */}
      <div className="homeTicket">
        <div className="ticketTop">
          <span className="span1">限时秒杀</span>
          <div className="time">
            <span class="hour">{H}</span> <strong>:</strong>
            <span class="minute">{M}</span> <strong>:</strong>
            <span class="second">{S}</span>
            {titles}
          </div>
          <span
            className="span2"
            onClick={() => {
              history.push({ pathname: '/limited', state: limList[0]._id });
            }}
          >
            查看全部
            <RightOutline />
          </span>
        </div>
        <div className="data">
          {limList.map((item) => {
            return <Limited {...item} key={item.id}></Limited>;
          })}
        </div>
      </div>
      <img src="/api/upload/banner1.jpg" className="banner" />
      <JumboTabs
        defaultActiveKey="1"
        activeKey={key}
        onChange={(key) => good(key)}
      >
        <JumboTabs.Tab title="为你推荐" description="超值好货" key={1}>
          {datalist.length != 0 ? (
            <div className="goods">
              {datalist.map((item1) => {
                return <Good {...item1} key={item1._id}></Good>;
              })}
            </div>
          ) : (
            <Empty description="暂无商品" style={{ margin: '0 auto' }} />
          )}
        </JumboTabs.Tab>
        {classify.map((item, index) => {
          return (
            <JumboTabs.Tab
              title={item.name}
              description={data2[index]}
              key={item._id}
            >
              {datalist.length != 0 ? (
                <div className="goods">
                  {datalist.map((item1) => {
                    return <Good {...item1} key={item1._id}></Good>;
                  })}
                </div>
              ) : (
                <Empty description="暂无商品" style={{ margin: '0 auto' }} />
              )}
            </JumboTabs.Tab>
          );
        })}
      </JumboTabs>
      {token ? '' : <Notlogin />}
    </div>
  );
}
